//
//  myOrderListViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-5-24.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "myOrderListViewController.h"
#import "UIImageView+WebCache.h"
#import "orderDetailViewController.h"
#import "MBProgressHUD.h"
#import "alipayViewController.h"

@interface myOrderListViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIView *emptyFooterView;
}

@end

@implementation myOrderListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItem];
    [self setupTableView];
    self.title = @"我的订单";
}

- (void)setupTableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    self.orderListTV.tableFooterView = view;
}

- (void)dataInit{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = NO;
    
    NSDictionary *params;
    
    if ([_type length] == 0||[_type isEqual:[NSNull null]] ) {
        params = @{@"memberid": _memberId,
                   @"access_token": _token,
                   @"pagesize": @"10",
                   @"pagenumber": @"1",
                   @"source":@"5,6"
                   };
    }else{
        params = @{@"memberid": _memberId,
                   @"access_token": _token,
                   @"status": _type,
                   @"pagesize": @"15",
                   @"pagenumber": @"1",
                   @"source":@"5,6"
                   };
    }
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"myzhenpin/getMemberOrderList.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *orderListsDic = (NSDictionary *)responseObject;
        self.orderlistArr = orderListsDic[@"result"];
        if ([self.orderlistArr count]==0) {
            [self showNoDataViewWithKeyWord:@"暂无订单"];
        } else {
            [self hideNoDataView];
        }
        [self.orderListTV reloadData];
        [HUD hide:YES afterDelay:1];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hide:YES afterDelay:1];
    }];
}

-(void)setNavigationItem {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)showNoDataViewWithKeyWord:(NSString *)key {
    NSString *str = [NSString stringWithFormat:@"%@",key];
    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:str];
//    [textStr addAttribute:NSForegroundColorAttributeName value:ColorFromRGB(0xff4400) range:NSMakeRange(6, key.length)];
    
    if (emptyFooterView) {
        UILabel *label = (UILabel*)[emptyFooterView viewWithTag:800];
        label.attributedText = textStr;
        emptyFooterView.hidden = NO;
        [self.view bringSubviewToFront:emptyFooterView];
    } else {
        int height;
        height = 528;
        emptyFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, height)];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
        imageView.center = CGPointMake(emptyFooterView.frame.size.width/2, (emptyFooterView.frame.size.height-220)/2);
        imageView.image = [UIImage imageNamed:@"no05"];
        [emptyFooterView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, (emptyFooterView.frame.size.height-240)/2+imageView.frame.size.height, 320, 30)];
        label.textColor = RGB(51, 51, 51);
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 800;
        label.attributedText = textStr;
        [emptyFooterView addSubview:label];
        emptyFooterView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:emptyFooterView];
    }
}
-(void)hideNoDataView {
    if (emptyFooterView) {
        emptyFooterView.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self dataInit];//在线支付后 可以实时获取支付状态
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  return self.orderlistArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *orderDic = [self.orderlistArr objectAtIndex:indexPath.section];
    UITableViewCell *cell;
    //支付类型  支付状态 订单状态
    if ([orderDic[@"payTypeId"] integerValue] == 2 && [orderDic[@"payStatus"] integerValue] != 1 && [orderDic[@"status"] integerValue] != 5 ) {
        cell = nil;
        cell =[tableView dequeueReusableCellWithIdentifier:@"orderCell"];
        UILabel *payStatus = (UILabel *)[cell viewWithTag:1];
        UILabel *orderSn = (UILabel *)[cell viewWithTag:2];
        UILabel *subTotal = (UILabel *)[cell viewWithTag:3];
        UILabel *orderTime = (UILabel *)[cell viewWithTag:4];
        UIButton *payButton = (UIButton *)[cell viewWithTag:5];
        UIImageView *pImgView = (UIImageView *)[cell viewWithTag:6];
        
        [pImgView sd_setImageWithURL:[NSURL URLWithString:orderDic[@"m_small"]] placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRetryFailed];
        NSInteger orderStatus = [orderDic[@"status"] integerValue];
        NSString *statusStr;
        switch (orderStatus) {
            case 0:
                statusStr = @"未审核";
                break;
            case 1:
                statusStr = @"已确认";
                break;
            case 2:
                statusStr = @"备货中";
                break;
            case 3:
                statusStr = @"已发货";
                break;
            case 4:
                statusStr = @"已完成";
                break;
            case 5:
                statusStr = @"已取消";
                break;
                
            default:
                statusStr = @"删除";
                break;
        }
        
        
        payStatus.text = statusStr;
        
        NSTimeInterval time=[[NSString stringWithFormat:@"%@",orderDic[@"createTime"]] doubleValue];//str是NSString类型
        NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"yyyy-MM-dd HH:mm";
        NSString *dateString = [df stringFromDate:timeDate];
        
        orderSn.text = [NSString stringWithFormat:@"%@",orderDic[@"orderSn"]];
        subTotal.text = [NSString stringWithFormat:@"￥%@",orderDic[@"totalAmount"]];
        //orderTime.text = [NSString stringWithFormat:@"%@",orderDic[@"createTime"]];
        orderTime.text = dateString;
        [payButton.layer setCornerRadius:4.0];
        [payButton addTarget:self action:@selector(alipay) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell = nil;
        cell =[tableView dequeueReusableCellWithIdentifier:@"noPayCell"];
        UILabel *payStatus = (UILabel *)[cell viewWithTag:1];
        UILabel *orderSn = (UILabel *)[cell viewWithTag:2];
        UILabel *subTotal = (UILabel *)[cell viewWithTag:3];
        UILabel *orderTime = (UILabel *)[cell viewWithTag:4];
        UIImageView *pImgView = (UIImageView *)[cell viewWithTag:6];
        
        [pImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",orderDic[@"m_small"]]] placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRetryFailed];
        
        NSInteger orderStatus = [orderDic[@"status"] integerValue];
        NSString *statusStr;
        switch (orderStatus) {
            case 0:
                statusStr = @"未审核";
                break;
            case 1:
                statusStr = @"已确认";
                break;
            case 2:
                statusStr = @"备货中";
                break;
            case 3:
                statusStr = @"已发货";
                break;
            case 4:
                statusStr = @"已完成";
                break;
            case 5:
                statusStr = @"已取消";
                break;
                
            default:
                statusStr = @"删除";
                break;
        }
        payStatus.text = statusStr;
//        payStatus.text = orderDic[@"paytypename"];
        NSTimeInterval time=[[NSString stringWithFormat:@"%@",orderDic[@"createTime"]] doubleValue];//str是NSString类型
        NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"yyyy-MM-dd HH:mm";
        NSString *dateString = [df stringFromDate:timeDate];
        
        orderSn.text = [NSString stringWithFormat:@"%@",orderDic[@"orderSn"]];
        subTotal.text = [NSString stringWithFormat:@"￥%@",orderDic[@"totalAmount"]];
        //orderTime.text = [NSString stringWithFormat:@"%@",orderDic[@"createTime"]];
        orderTime.text = dateString;
    }
    return cell;
}

-(void)alipay{
    
    NSIndexPath *path = [self.orderListTV indexPathForSelectedRow];
    NSDictionary *orderDic = [self.orderlistArr objectAtIndex:path.section];

    alipayViewController *destVC = [self.storyboard instantiateViewControllerWithIdentifier:@"alipayViewController"];
    UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:destVC];
    destVC.memberId  = _memberId;
    destVC.token    = _token;
    destVC.orderId = [NSString stringWithFormat:@"%@",orderDic[@"orderId"]];
    destVC.ordersn = [NSString stringWithFormat:@"%@",orderDic[@"orderSn"]];
    destVC.needpay = [NSString stringWithFormat:@"%@",orderDic[@"needPay"]];
    navigationVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navigationVC.navigationBar.tintColor = [UIColor blackColor];
    // present
    [self presentViewController:navigationVC animated:YES completion:nil];
    
}
- (NSDate*)dateFromUnixTimestamp:(NSTimeInterval)timestamp {
    return [NSDate dateWithTimeIntervalSince1970:timestamp];
}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (cell) {
//        [[cell.contentView viewWithTag:500] removeFromSuperview];
//    }
//    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, cell.frame.size.height - 10, cell.frame.size.width, 10)];
//    [bgView setBackgroundColor:BACKGROUND_COLOR];
//    bgView.tag = 500;
//    [cell.contentView addSubview:bgView];
//}
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *orderDic = [self.orderlistArr objectAtIndex:indexPath.section];
    CGFloat cellRowHeight;
    if ([orderDic[@"payTypeId"] integerValue] == 2 && [orderDic[@"payStatus"] integerValue] != 1 && [orderDic[@"status"] integerValue] != 5 ) {
        cellRowHeight  = 170;
    }else{
        cellRowHeight  = 120;
    }
    return cellRowHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *path = [self.orderListTV indexPathForSelectedRow];
    orderDetailViewController *destVC = segue.destinationViewController;
    destVC.memberId  = _memberId;
    destVC.token    = _token;
    NSDictionary *orderDic = [self.orderlistArr objectAtIndex:path.section];
    destVC.orderId = [NSString stringWithFormat:@"%@",orderDic[@"orderId"]];
    destVC.ordersn = [NSString stringWithFormat:@"%@",orderDic[@"orderSn"]];
    destVC.needpay = [NSString stringWithFormat:@"%@",orderDic[@"needPay"]];
}
@end
